from openpyxl import load_workbook
from config import filepath, export_path
import json

wb = load_workbook(filepath, read_only=True)

data = dict()

def parseData(t, value):
    if value is None:
        return None
    if t == 'number':
        value = int(value)
    elif t == 'string':
        value = str(value)
    elif t == 'array':
        arr = str(value).split(',')
        value = list(map(int, arr))
    return value
    
for sheet in wb:
    tableName = sheet['A1'].value
    tableType = sheet['B1'].value

    if tableType == 'relation':
        data[tableName] = []
    else:
        data[tableName] = {}

    keys = []
    for i in range(sheet.max_column):
        keys.append(sheet.cell(row=3, column=i+1).value)
    
    types = []
    for i in range(sheet.max_column):
        types.append(sheet.cell(row=4, column=i+1).value)

    for i in range(5, sheet.max_row + 1):
        row = dict()
        if sheet.cell(row=i, column=1).value == None:
            continue
        for j in range(sheet.max_column):
            if keys[j] is None:
                continue
            try:
                value = parseData(types[j], sheet.cell(row=i, column=j + 1).value)
                row[keys[j]] = value
            except:
                print('error')
                print('type: {}, value: {}'.format(types[j], sheet.cell(row=i, column=j + 1).value))
                print('{}: row: {}, column: {}'.format(tableName, i, j))
        if tableType == 'relation':
            data[tableName].append(row)
        else:
            data[tableName] = row
    # break
# print(data)
r = json.dumps(data)

r = "export const globalConfig = " + r

text_file = open(export_path, "w")
text_file.write(r)
text_file.close()

    # print(type(sheet.rows))
